<template>
  <div class="flex-column container">
    <div class="header radius shadow">
      <el-form :inline="true" class="form">
        <el-form-item label="职位名称:">
          <el-input
            placeholder="请你输入搜索的职位名称"
            v-model="keyword"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="default"
            :disabled="keyword.length ? false : true"
            @click="search"
          >
            搜索
          </el-button>
          <el-button size="default" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="content shadow radius flex-column">
      <div class="addHeader">
        <el-button type="primary" size="default" icon="Plus" @click="addRole">
          添加职位
        </el-button>
      </div>
      <!-- 表格 -->
      <el-table
        class="two-table"
        border
        :data="data.tableData"
        style="height: 100%; width: 100%"
      >
        <el-table-column
          label="#"
          width="80"
          type="index"
          :index="1 + data.pageSize * (data.currentPage - 1)"
          align="center"
        ></el-table-column>
        <el-table-column label="ID" prop="id" width="80"></el-table-column>
        <el-table-column
          label="角色名称"
          prop="roleName"
          width="160"
        ></el-table-column>
        <el-table-column label="创建时间" prop="createTime"></el-table-column>
        <el-table-column label="更新时间" prop="updateTime"></el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template #default="scope">
            <el-button
              size="small"
              icon="User"
              @click="setPermission(scope.row)"
            >
              分配权限
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateRole(scope.row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`你确定要删除${scope.row.roleName}?`"
              width="260px"
              @confirm="removeRole(scope.row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="data.currentPage"
          v-model:page-size="data.pageSize"
          :page-sizes="[20, 40, 50, 80]"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper,->sizes,total"
          :total="data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加职位-角色 -->
    <el-dialog
      v-model="dialogVisible"
      :title="RoleParams.id ? '更新职位' : '添加职位'"
    >
      <el-form :model="RoleParams" :rules="rules" ref="form">
        <el-form-item label="职位名称" prop="roleName">
          <el-input
            placeholder="请你输入职位名称"
            v-model="RoleParams.roleName"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="default" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="default" @click="save">确定</el-button>
      </template>
    </el-dialog>
    <!-- 分配菜单与按钮的权限 -->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>分配菜单与按钮的权限</h4>
      </template>
      <template #default>
        <el-tree
          ref="tree"
          :data="menuArr"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="selectArr"
          :props="defaultProps"
        />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="handler">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, nextTick } from "vue";
import { ElMessage,  } from "element-plus";
import {
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqSetPermission,
  reqRemoveRole,
} from "../../../api/acl/role/index";
import type {
  RoleData,
  RoleResponseData,
  MenuResponseData,
  MenuList,
} from "../../../api/acl/role/type";
// 获取骨架的小仓库
import useLayoutSettingsStore from "../../../store/modules/settings";

let settingStore = useLayoutSettingsStore();
const background = ref(true);
const size = ref("default");
const disabled = ref(false);

const keyword = ref("");
const data = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  tableData: [],
});
// 获取form组件实例
let form = ref<any>();
let dialogVisible = ref<boolean>(false);
// 控制抽展显示与隐藏
let drawer = ref<boolean>(false);
// 定义数组存储用户权限的数据
let menuArr = ref<MenuList>([]);
let selectArr = ref<number[]>([]);
let tree = ref<any>();

// 收集新增岗位数据
let RoleParams = reactive<RoleData>({
  roleName: "",
});

const defaultProps = {
  children: "children",
  label: "name",
};

onMounted(() => {
  getRoleList();
});

// 获取角色列表
const getRoleList = async () => {
  const res: RoleResponseData = await reqAllRoleList(
    data.currentPage,
    data.pageSize,
    keyword.value,
  );
  if (res.code === 200) {
    data.tableData = res.data.records as [];
    data.total = res.data.total;
  }
};
// 分页事件
//当下拉菜单发生变化的时候触发次方法
//这个自定义事件,分页器组件会将下拉菜单选中数据返回
const handleSizeChange = (val: number) => {
  console.log(`每页 ${val} 条`);
  data.pageSize = val;
  data.currentPage = 1;
  getRoleList();
};

const handleCurrentChange = (val: number) => {
  console.log(`当前页: ${val}`);
  data.currentPage = val;
  getRoleList();
};

// 搜索重置
const search = () => {
  getRoleList();
  keyword.value = "";
};
const reset = () => {
  settingStore.refsh = !settingStore.refsh;
};
// 添加角色
const addRole = () => {
  dialogVisible.value = true;
  Object.assign(RoleParams, {
    roleName: "",
    id: 0,
  });
  // 清除上一次表单校验出现的错误
  nextTick(() => {
    form.value.clearValidate("roleName");
  });
};

// 编辑角色
const updateRole = async (row: any) => {
  dialogVisible.value = true;
  Object.assign(RoleParams, row);
  nextTick(() => {
    form.value.clearValidate("roleName");
  });
};

// 添加角色的保存
const save = async () => {
  await form.value.validate();
  let res: any = await reqAddOrUpdateRole(RoleParams);
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: RoleParams.id ? "更新成功" : "添加成功",
    });
    dialogVisible.value = false;
    data.currentPage = RoleParams.id ? data.currentPage : 1;
    getRoleList();
  }
};

// 分配权限
const setPermission = async (row: any) => {
  drawer.value = true;
  Object.assign(RoleParams, row);
  // 根据职位获取权限的数据
  let res: MenuResponseData = await reqAllMenuList(RoleParams.id as number);
  if (res.code === 200) {
    menuArr.value = res.data;
    selectArr.value = filterSelectArr(menuArr.value, []);
  }
};
const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level === 4) {
      initArr.push(item.id);
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr);
    }
  });
  return initArr;
};
// 分配权限的确定
const handler = async () => {
  const roleId = RoleParams.id as number;
  let arr = tree.value.getCheckedKeys();
  let arr1 = tree.value.getHalfCheckedKeys();
  let permissionId = arr.concat(arr1);
  let res: any = await reqSetPermission(roleId, permissionId);
  if (res.code === 200) {
    drawer.value = false;
    ElMessage({
      type: "success",
      message: "分配权限成功",
    });
    window.location.reload();
  }
};

// 删除角色
const removeRole = async (rowId: any) => {
  let res: any = await reqRemoveRole(rowId);
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    data.currentPage = data.tableData.length > 1 ? data.currentPage : 1;
    getRoleList();
  }
};

// 添加角色的规则
const validateRoleName = (rule: any, value: any, callBack: any) => {
  console.log(rule);
  if (value.trim().length >= 2) {
    callBack();
  } else {
    callBack(new Error("职位名称至少两位"));
  }
};

const rules = {
  roleName: [{ required: true, trigger: "blur", validator: validateRoleName }],
};
</script>

<style scoped lang="scss">
@import "@/styles/common.scss";

.header {
  padding: 10px;
  box-sizing: border-box;
  height: 60px;
  width: 100%;
  margin-bottom: 10px;

  .form {
    margin-top: 5px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.content {
  flex: 1;
  box-sizing: border-box;
  overflow: hidden;
  padding: 12px;

  .addHeader {
    height: 40px;
    width: 100%;
    margin-bottom: 5px;
  }
}
</style>
